<?php
namespace plugin\ky_shouyin\app\controller;

use support\Request;
use support\Db;

class PointsRuleController extends BaseController
{
    public function index()
    {
        return $this->view('points/rule/index');
    }
    
    public function list(Request $request)
    {
        $rules = Db::table('ky_points_rule')->get();
        return json(['code' => 0, 'msg' => 'success', 'data' => $rules]);
    }
    
    public function save(Request $request)
    {
        $data = $request->post();
        $id = $data['id'] ?? null;
        
        try {
            $saveData = [
                'name' => $data['name'],
                'type' => $data['type'],
                'condition' => $data['condition'],
                'points' => $data['points'],
                'status' => $data['status'],
                'description' => $data['description'],
                'updated_at' => date('Y-m-d H:i:s')
            ];
            
            if ($id) {
                Db::table('ky_points_rule')->where('id', $id)->update($saveData);
            } else {
                $saveData['created_at'] = date('Y-m-d H:i:s');
                Db::table('ky_points_rule')->insert($saveData);
            }
            
            return json(['code' => 0, 'msg' => '保存成功']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '保存失败：' . $e->getMessage()]);
        }
    }
    
    public function delete(Request $request)
    {
        $id = $request->post('id');
        
        try {
            Db::table('ky_points_rule')->where('id', $id)->delete();
            return json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }
    
    public function setStatus(Request $request)
    {
        $id = $request->post('id');
        $status = $request->post('status');
        
        try {
            Db::table('ky_points_rule')
                ->where('id', $id)
                ->update(['status' => $status]);
            return json(['code' => 0, 'msg' => '设置成功']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '设置失败：' . $e->getMessage()]);
        }
    }
} 